package com.yxc.easyexceldemo.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.yxc.easyexceldemo.const_enum.MEnum;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 枚举自定义转换器
 *
 * @author: YXC
 * @time: 2022/11/15 14:51
 **/
public class EnumConvert implements Converter<MEnum> {

    Map<String, MEnum[]> cache = new HashMap<>();

    @Override
    public Class<?> supportJavaTypeKey() {
        return MEnum.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public MEnum convertToJavaData(ReadConverterContext<?> context) throws Exception {
        String stringValue = context.getReadCellData().getStringValue();
        Class<MEnum> fieldType = getFieldType(context);

        return MEnum.staticGetByName(fieldType, stringValue);
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<MEnum> context) throws Exception {
        return new WriteCellData<>(context.getValue().getName());
    }

    private Class<MEnum> getFieldType(ReadConverterContext<?> context) {
        return (Class<MEnum>) context.getContentProperty().getField().getType();
    }
}
